﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using ExtremeSwank.Authentication.OpenID.Plugins.Extensions;
using System.Web;

namespace ExtremeSwank.Authentication.OpenID
{
    /// <summary>
    /// Receive and process unsolicited Attribute Exchange assertion messages.
    /// </summary>
    public class AXReceiver
    {
        StateContainer rp;

        /// <summary>
        /// Creates a new instance of AXReceiver.
        /// </summary>
        public AXReceiver()
        {
            rp = new StateContainer();
            rp.RequestArguments = HttpContext.Current.Request.Params;
        }

        /// <summary>
        /// Creates a new instance of AXReceiver.
        /// </summary>
        /// <param name="arguments">A collection of arguments received from a request.</param>
        public AXReceiver(NameValueCollection arguments)
        {
            rp = new StateContainer();
            rp.RequestArguments = arguments;
        }

        /// <summary>
        /// Whether or not the request is an OpenID assertion.
        /// </summary>
        /// <returns>True if it is, false if not.</returns>
        private bool CheckMode()
        {
            if (Utility.GetRequestedMode(rp.RequestArguments) == RequestedMode.IdResolution)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// Check with the OpenID Server to ensure the message is valid.
        /// </summary>
        /// <returns>True if the validation was successful, false if not.</returns>
        public bool Validate()
        {
            if (CheckMode())
            {
                Utility.UpdateIdentity(rp.RequestArguments["openid.identity"], rp);
                string openidServer = Utility.GetOpenIDServer(rp);
                return Utility.ValidateStatelessRequest(openidServer, false, rp);
            }
            return false;
        }

        /// <summary>
        /// The OpenID Identity included in the assertion.
        /// </summary>
        public string Identity
        {
            get { return rp.Identity; }
        }

        /// <summary>
        /// The OpenID Identity URL associated with the assertion.
        /// </summary>
        public string IdentityUrl
        {
            get { return rp.IdentityURL; }
        }

        /// <summary>
        /// Retrieves and decodes Attribute Exchange data items.  
        /// </summary>
        /// <returns>An array of decoded AttributeExchangeItem objects.</returns>
        public AttributeExchangeItem[] GetItems()
        {
            return Plugins.Extensions.AttributeExchange.DecodeUserData(rp.RequestArguments);
        }
    }
}
